package com.example.shushiyunsst.fragment.main.home.recycler.view

import android.content.Context
import android.support.v4.media.session.PlaybackStateCompat
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import com.example.library_common.glidmodule.GlideApp
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.recycler.bean.advise_bean.AdviseVideoEntity
import com.example.shushiyunsst.util.media.MediaControllerManager
import com.example.shushiyunsst.util.media.MediaExoPlayerManager
import com.google.android.exoplayer2.ui.PlayerView

class AdviseVideoView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    FrameLayout(context, attrs, defStyleAttr), View.OnClickListener, IPlayTarget {

    companion object {
        private const val TAG = "AdviseVideoView"
    }

    private var videoView: View

    private var playerView: PlayerView

    private var mProgressBar: ProgressBar

    private var maskView: View

    private var maskImg: ImageView

    private var statusAvatar: ImageView

    private var maskPayingAvatar: View

    private var position: TextView

    private var mEntity: AdviseVideoEntity? = null

    private val mediaControllerManager = MediaControllerManager.get()

    private var mViewLifecycleOwner: LifecycleOwner? = null

    private var isConnected = false

    init {

        inflate(context, R.layout.advise_video_view, this)
        position = findViewById(R.id.position)
        videoView = findViewById(R.id.videoView)
        playerView = findViewById(R.id.playerView)
        mProgressBar = findViewById(R.id.mProgressBar)
        maskView = findViewById(R.id.maskView)
        maskImg = findViewById(R.id.maskImg)
        statusAvatar = findViewById(R.id.statusAvatar)
        maskPayingAvatar = findViewById(R.id.maskPayingAvatar)
        maskPayingAvatar.setOnClickListener(this)
//        getPlayer()
//        playerView.player = getPlayer()
    }


    fun setViewLifecycleOwner(viewLifecycleOwner: LifecycleOwner?) {
        if (mViewLifecycleOwner != null) return
        mViewLifecycleOwner = viewLifecycleOwner
        mViewLifecycleOwner.let {
            if (it != null) {
                mediaControllerManager.playbackState.observe(it, { mit ->
                    post {
                        if (isEquals()) {
                            handlePlaybackState(mit)
                        }
                    }
                })
            }
        }
    }

    fun showMaskView(mEntity: AdviseVideoEntity?) {
        this.mEntity = mEntity
        position.text = "${mEntity?.uiPos}"
        showMaskView()
        GlideApp.with(this)
            .load(mEntity?.modUrl)
            .centerCrop()
            .placeholder(R.drawable.img_erros_bg_rect)
            .into(maskImg)
    }

    private fun showMaskView() {
        if (maskView.visibility== View.VISIBLE){
            return
        }
        maskView.visibility = View.VISIBLE
        videoView.visibility = View.GONE

    }

    private fun showVideoView() {
        if (videoView.visibility== View.VISIBLE){
            return
        }
        maskView.visibility = View.GONE
        videoView.visibility = View.VISIBLE
    }

    private fun onPause() {
        mediaControllerManager.pause()
        mEntity?.isPlaying = false
    }

    fun onStop() {
        mediaControllerManager.stop()
        mEntity?.isPlaying = false

    }

    private fun onStart() {
        mediaControllerManager.play()
        mEntity?.isPlaying = true
    }


    private fun handlePlaybackState(mit: PlaybackStateCompat?) {
        if (mit != null) {
//            Log.d(TAG, "uiPos: ${mEntity?.uiPos}")
            Log.d(TAG, "mit.state: ${mit.state}")

            when (mit.state) {

                PlaybackStateCompat.STATE_BUFFERING -> {

                    showVideoView()
                    if (mProgressBar.visibility != View.VISIBLE) {
                        mProgressBar.visibility = View.VISIBLE
                    }
                }
                PlaybackStateCompat.STATE_PAUSED -> {

                    showMaskView()

                    mEntity?.isPlaying = false

                    val manager = PageListPlayManager.getInstance()
                    if (!manager.isPauseByInActive) {
                        manager.isStartedPaying = false
                    }
                    Log.d(TAG, "STATE_PAUSED: ${mEntity?.uiPos}")
                }
                PlaybackStateCompat.STATE_STOPPED -> {
                    showMaskView()
                    mEntity?.isPlaying = false
                    val manager = PageListPlayManager.getInstance()
                    if (!manager.isPauseByInActive) {
                        manager.isStartedPaying = false
                    }
                }

                PlaybackStateCompat.STATE_ERROR -> {
                    showMaskView()
                    mEntity?.isPlaying = false
                }

                PlaybackStateCompat.STATE_PLAYING -> {
                    showVideoView()
                    mEntity?.isPlaying = true
                    if (mProgressBar.visibility != View.GONE) {
                        mProgressBar.visibility = View.GONE
                    }
                }
                else -> {
                    if (mProgressBar.visibility != View.GONE) {
                        mProgressBar.visibility = View.GONE
                    }
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.maskPayingAvatar -> {
                if (isPlaying) {
                    return
                }
                val manager = PageListPlayManager.getInstance()
                manager.isStartedPaying = true

                onActive()
            }
        }
    }

    private fun isEquals(preItem: AdviseVideoEntity?): Boolean {
        val preUrl = preItem?.targetUrl ?: ""
        val preAid = preItem?.aid ?: -100

        val currentUrl = mEntity?.targetUrl ?: ""
        val currentAid = mEntity?.aid ?: -120

        return preUrl == currentUrl
                && currentUrl.isNotEmpty()
                && preAid == currentAid
    }

    private fun isEquals(): Boolean {
        val manager = PageListPlayManager.getInstance()
        val item = manager.currentItem

        val preUrl = item?.targetUrl ?: ""
        val preAid = item?.aid ?: -100

        val currentUrl = mEntity?.targetUrl ?: ""
        val currentAid = mEntity?.aid ?: -120

        return preUrl == currentUrl
                && currentUrl.isNotEmpty()
                && preAid == currentAid

    }

    override fun getOwner(): ViewGroup {
        return this
    }

    override fun onActive() {
        val manager = PageListPlayManager.getInstance()

        if (!manager.isStartedPaying) return

        if (!isPlaying) {

            val prePayer: AdviseVideoView? = manager.currentPayer

            if (!isEquals(manager.currentItem)) {
                prePayer?.inActive()
            }
            if (playerView.player == null) {
                if (prePayer == null) {
                    playerView.player = getPlayer()
                } else {
                    PlayerView.switchTargetView(getPlayer(), prePayer.playerView, playerView)
                }

            }

            manager.currentPayer = this
            manager.currentItem = mEntity
//
            manager.isPauseByInActive = false
            mEntity?.isPlaying = true


            playVideo(mEntity?.targetUrl)
        } else if (isEquals()) {
            onStart()

        }

    }

    override fun inActive() {
        if (isEquals()) {
            Log.d(TAG, "inActive: ${mEntity?.uiPos}")
            val manager = PageListPlayManager.getInstance()
            manager.isPauseByInActive = true
            onPause()
            showMaskView()
        }

    }

    override fun isPlaying(): Boolean {
        return mEntity?.isPlaying ?: false
    }

    private fun getPlayer() = MediaExoPlayerManager.get().exoPlayer

    private fun playVideo(url: String?) {
        if (!isConnected) {
            isConnected = mediaControllerManager.isConnected.value == true
        }
        if (isConnected) {
            mediaControllerManager.playVideo(url)
        } else {
            postDelayed({
                playVideo(mEntity?.targetUrl)
            }, 200)
        }
    }
}